package cn.com.dhc.danlu.activity.home.presenter;

import android.app.Activity;

import com.danlu.dlsms.model.pub.res.MsgCountResponse;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.com.dhc.danlu.activity.home.presenter.HomeContract.IHomeView;
import cn.com.dhc.danlu.constant.MsgTypeConst;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.util.CommonConst;
import cn.com.dhc.danlu.widget.loadlayer.LayerEnum;
import cn.com.hd.mall.web.webservices.entity.freedom.request.base.BaseRequest;
import cn.com.hd.mall.web.webservices.entity.freedom.request.base.BasePageRequest;
import cn.com.hd.mall.web.webservices.entity.request.pushmsg.GetUnreadCountRequest;
import cn.com.hd.mall.web.webservices.entity.response.common.GetBannerListResponse;
import cn.com.hd.mall.web.webservices.entity.response.common.GetBannerListResponse.BannerListModel;
import cn.com.hd.mall.web.webservices.entity.response.common.GetTopicListResponse;
import cn.com.hd.mall.web.webservices.entity.response.merch.PromotionListResponse;
import cn.com.hd.mall.web.webservices.entity.response.merch.RecommendListResponse;
import cn.com.hd.mall.web.webservices.entity.response.merch.base.BaseMerchListModel;
import cn.com.hd.mall.web.webservices.entity.response.order.OrderCountResponse;
import cn.com.hd.mall.web.webservices.entity.response.order.OrderCountResponse.OrderCount;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;

/**
 * @author wuhaiyang
 */
public class HomePresenter {
    private IHomeView mView;
    private boolean isLoadTypeSuc = false;

    private int mPageSize = 4;
    private int mPromotionPage = 1;
    private int mPromotionTotalPageCount;
    private int mRecommenedPage = 1;
    private int mRecommenedTotalPageCount;

    /**
     * 标识当前是否正在加载促销列表
     */
    private LayerEnum mLoadPromotionStatus;
    private LayerEnum mLoadRecommendedStatus;


    public HomePresenter() {
        super();
    }

    /**
     * 界面可见的时候回调 : 刷新未读消息数量 + 我的订单数量 + 我的红包数量
     */
    public void onStart() {
        if (isLoadTypeSuc) {
            // 请求服务器获取未读消息数量
            getUnreadMsgCountRequest();
            // 获取我的订单数量
            getMyOrderCount();

            if (mLoadPromotionStatus == LayerEnum.layer_empty || mLoadPromotionStatus == LayerEnum.layer_error) {
                refreshMerchList(true);
            }
            if (mLoadRecommendedStatus == LayerEnum.layer_empty || mLoadRecommendedStatus == LayerEnum.layer_error) {
                refreshMerchList(false);
            }
        }
    }

    /**
     * 获取未读消息数目
     */
    public void getUnreadMsgCountRequest() {
        GetUnreadCountRequest request = new GetUnreadCountRequest();
        request.receiverUserId = agent.getLoginUser().getUserId();
        request.receiverCompanyId = agent.getLoginUser().getCompanyId();
        request.channelId = CommonConst.CHANNEL_ID;
        agent.getMsgApi()
                .getUnreadMsgCount(request)
                .compose(OperatorUtils.<MsgCountResponse>defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<MsgCountResponse>() {
                    @Override
                    protected void onSuccess(MsgCountResponse model) {
                        if (!checkIsHostExit()) {
                            return;
                        }
                        Map<String, Integer> unreadMap = model.getMsgCount().getUnreadCount();
                        int unreadOrderMsg = unreadMap.get(MsgTypeConst.MsgTypeGroup.PURCHASE_ORDER_MSG);
                        int unreadOtherMsg = unreadMap.get(MsgTypeConst.MsgTypeGroup.MY_MSG);
                        // 未读红包消息数量
                        int unreadEnvelopMsg = 0;
                        if (null != unreadMap.get(MsgTypeConst.MsgTypeGroup.DANLU_ENVELOP_MSG)) {
                            unreadEnvelopMsg = unreadMap.get(MsgTypeConst.MsgTypeGroup.DANLU_ENVELOP_MSG);
                        }
                        //当前实现类可能会被销毁
                        if (null != mView) {
                            mView.refreshBadgeCount(HomeContract.MsgCountType.push_msg, unreadOrderMsg + unreadOtherMsg + unreadEnvelopMsg);
                        }
                    }
                });
    }

    /**
     * 获取订单数量
     */
    private void getMyOrderCount() {
        BaseRequest request = new BaseRequest();
        request.setToken(agent.getToken());
        agent.getApi().getTerminalOrderCount(request)
                .compose(OperatorUtils.<OrderCountResponse>defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<OrderCountResponse>() {
                    @Override
                    protected void onSuccess(OrderCountResponse model) {
                        if (!checkIsHostExit()) {
                            return;
                        }
                        OrderCount orderCount = model.getOrderCount();
                        int totalCount = Integer.parseInt(orderCount.getPendingPaymentOrderCount()) + Integer.parseInt(orderCount.getWaitingShipmentOrderCount()) + Integer.parseInt(orderCount.getWaitingReceiveOrderCount());
                        mView.refreshBadgeCount(HomeContract.MsgCountType.order, totalCount);
                    }
                });
    }

    /**
     * 刷新丹露促销列表 & 丹露推荐
     */
    public void refreshMerchList(final boolean isPromotion) {
        if (isPromotion) {
            mLoadPromotionStatus = LayerEnum.layyer_loading;
        } else {
            mLoadRecommendedStatus = LayerEnum.layyer_loading;
        }
        mView.showRotateBar(isPromotion);
        BasePageRequest request = new BasePageRequest();
        request.setPage(isPromotion ? mPromotionPage : mRecommenedPage);
        request.setRows(mPageSize);
        request.setToken(agent.getToken());
        if (isPromotion) {
            agent.getApi()
                    .getPromotionList(request)
                    .compose(OperatorUtils.<PromotionListResponse>defaultSchedulers())
                    .subscribe(new GeneralBusinessObserver<PromotionListResponse>() {
                        @Override
                        protected void onSuccess(PromotionListResponse model) {
                            int totalCount = Integer.valueOf(model.getTotalRecord());
                            mPromotionTotalPageCount = calculateTotalPage(totalCount);
                            if (null != model.getPromotionListModel()) {
                                calculatePaging(model.getPromotionListModel().size(), mPromotionTotalPageCount, true);
                                mView.setPromotionList(model, totalCount);
                                if (model.getPromotionListModel().isEmpty()) {
                                    mLoadPromotionStatus = LayerEnum.layer_empty;
                                } else {
                                    mLoadPromotionStatus = LayerEnum.layer_success;
                                }
                            } else {
                                mLoadPromotionStatus = LayerEnum.layer_empty;
                                mView.setRecommendList(new RecommendListResponse(), -1);
                            }
                        }

                        @Override
                        protected void onAlertTips(String displayMessage) {
                            if (!checkIsHostExit()) {
                                return;
                            }
                            mLoadPromotionStatus = LayerEnum.layer_error;
                            mView.getMerchListError(isPromotion, displayMessage);
                        }
                    });
        } else {
            agent.getApi()
                    .getRecommendList(request)
                    .compose(OperatorUtils.<RecommendListResponse>defaultSchedulers())
                    .subscribe(new GeneralBusinessObserver<RecommendListResponse>() {
                        @Override
                        protected void onSuccess(RecommendListResponse model) {
                            int totalCount = Integer.valueOf(model.getTotalRecord());
                            mRecommenedTotalPageCount = calculateTotalPage(totalCount);
                            if (null != model.getRecommendListModel()) {
                                calculatePaging(model.getRecommendListModel().size(), mRecommenedTotalPageCount, false);
                                if (model.getRecommendListModel().isEmpty()) {
                                    mLoadRecommendedStatus = LayerEnum.layer_empty;
                                } else {
                                    mLoadRecommendedStatus = LayerEnum.layer_success;
                                }
                                mView.setRecommendList(model, totalCount);
                            } else {
                                mLoadRecommendedStatus = LayerEnum.layer_empty;
                                mView.setRecommendList(new RecommendListResponse(), -1);
                            }
                        }

                        @Override
                        protected void onAlertTips(String displayMessage) {
                            if (!checkIsHostExit()) {
                                return;
                            }
                            mLoadRecommendedStatus = LayerEnum.layer_error;
                            mView.getMerchListError(isPromotion, displayMessage);
                        }
                    });
        }
    }

    /**
     * 检测宿主activity是否存货
     */
    public boolean checkIsHostExit() {
        return !(mView == null || null == mView.getContext() || ((Activity) mView.getContext()).isFinishing());
    }

    private int calculateTotalPage(int totalCount) {
        int i = totalCount % mPageSize;
        int pageCount = 0;
        if (i == 0) {
            pageCount = totalCount / mPageSize;
        } else {
            pageCount = totalCount / mPageSize + 1;
        }
        return pageCount;
    }

    private void calculatePaging(int size, int totalPage, boolean isPromotion) {
        if (size == 0) {
            if (isPromotion) {
                mPromotionPage = 1;
            } else {
                mRecommenedPage = 1;
            }
            return;
        }
        if (size >= mPageSize) {
            if (isPromotion) {
                mPromotionPage++;
            } else {
                mRecommenedPage++;
            }
        } else {
            if (isPromotion) {
                mPromotionPage = 1;
            } else {
                mRecommenedPage = 1;
            }
        }
        if (isPromotion) {
            mPromotionPage = mPromotionPage > totalPage ? 1 : mPromotionPage;
        } else {
            mRecommenedPage = mRecommenedPage > totalPage ? 1 : mRecommenedPage;
        }
    }

    /**
     * 首先先获取品牌类型model 回调成功后 ll_layer
     */
    public void fetchTypeDatas() {
        BaseRequest request = new cn.com.hd.mall.web.webservices.entity.freedom.request.base.BaseRequest();
        request.setToken(agent.getToken());
        agent.getApi()
                .getTopicList(request)
                .compose(OperatorUtils.<GetTopicListResponse>defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<GetTopicListResponse>() {
                    @Override
                    protected void onSuccess(GetTopicListResponse model) {
                        fillListViewHeaderSource(model);
                        // 请求获取banner 广告条内容
                        getBanner();
                        isLoadTypeSuc = true;
                        getMyOrderCount();
                        getUnreadMsgCountRequest();
                        initDoubleList();
                        refreshMerchList(true);
                        refreshMerchList(false);
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        if (mView != null) {
                            mView.switchLayer(LayerEnum.layer_error, displayMessage);
                        }
                    }
                });
    }

    /**
     * 在获取品牌类型数据成功的时候 开始绑定Header //接口调试的时候添加一个形参
     */
    private void fillListViewHeaderSource(GetTopicListResponse model) {
        if (null == mView && null == mView.getContext()) {
            return;
        }
        mView.refreshTopicList(model);
        mView.switchLayer(LayerEnum.layer_success, null);
    }

    /**
     * 获取广告条
     */
    private void getBanner() {
        BaseRequest request = new BaseRequest();
        request.setToken(agent.getToken());
        agent.getApi().getBannerList(request)
                .compose(OperatorUtils.<GetBannerListResponse>defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<GetBannerListResponse>() {
                    @Override
                    protected void onSuccess(GetBannerListResponse model) {
                        if (null != model.getBannerList() && !model.getBannerList().isEmpty())
                            divideBanner(model.getBannerList());
                    }
                });
    }

    /**
     * 两个List占位
     */
    private void initDoubleList() {
        List<BaseMerchListModel> modelList = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            modelList.add(new BaseMerchListModel());
        }

        RecommendListResponse recommendList = new RecommendListResponse();
        recommendList.setRecommendListModel(modelList);
        PromotionListResponse promotionList = new PromotionListResponse();
        promotionList.setPromotionListModel(modelList);

        mView.setPromotionList(promotionList, -1);
        mView.setRecommendList(recommendList, -1);
    }

    // 以及数据列表Adapter(后期添加)

    private void divideBanner(List<BannerListModel> bannerList) {
        List<BannerListModel> mTopBanners = new ArrayList<>();
        List<BannerListModel> mWaistBanners = new ArrayList<>();
        for (BannerListModel model : bannerList) {
            if (model.getBannerType().equals("B01")) {
                mTopBanners.add(model);
            } else if (model.getBannerType().equals("B02")) {
                mWaistBanners.add(model);
            }
        }
        mView.refreshViewModule(mTopBanners, true);
        if (!mWaistBanners.isEmpty()) {
            mView.refreshViewModule(mWaistBanners, false);
        }
    }

    public void attachView(IHomeView view) {
        this.mView = view;
    }

    public void detachView() {
        //        this.mView = null;
    }
}